package hashtable;

import java.util.*;

/**
 * @Classname : GroupAnagrams
 * @Description : 49. 字母异位词分组
 * https://leetcode.cn/problems/group-anagrams/
 * @Author : chentianyu
 * @Date 2023/3/18 00:33
 */


public class GroupAnagrams {
    public List<List<String>> groupAnagrams(String[] strs) {
        List<List<String>> ans = new ArrayList<>();
        Map<String, List<String>> map = new HashMap<>();

        for (String str : strs) {
            map.computeIfAbsent(getKey(str), x->new ArrayList<>()).add(str);
        }

        for (Map.Entry<String, List<String>> entry : map.entrySet()) {
            ans.add(entry.getValue());
        }
        return ans;
    }

    // 使用字符排序后的字符串作为Map的键
    private String getKey(String s) {
        char[] cs = s.toCharArray();
        Arrays.sort(cs);
        return String.valueOf(cs);
    }
}
